package com.alibaba.csp.sentinel.dashboard.repository.metric.influx;

import com.google.common.collect.Lists;
import org.influxdb.dto.QueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author ZHUFEIFEI
 */
public class InfluxMetricEntityConverter {

    private static final Logger log = LoggerFactory.getLogger(InfluxMetricEntityConverter.class);

    public static <R> List<R> toEntity(QueryResult.Series series, Class<R> clazz) {
        List<String> cols = series.getColumns();
        List<List<Object>> vals = series.getValues();
        final List<R> result = Lists.newArrayList();
        try {
            for (List<Object> item : vals) {
                R r = clazz.newInstance();
                for (int i=0; i < cols.size(); i++) {
                    setValue(r, cols.get(i), item.get(i));
                }
                result.add(r);
            }
        } catch (Exception e) {
            log.error("toEntity fail => {} error: {}",clazz, e.toString());
        }
        return null;
    }

    private static <R> void setValue(R o, String name, Object value) {
        try {
            Field f = o.getClass().getDeclaredField(name);
            f.setAccessible(true);
            f.set(o, value);
        } catch (NoSuchFieldException e) {
            log.error("setValue fail => {}:{} error: {}",name, value, e.toString());
        } catch (IllegalAccessException e) {
            log.error("setValue fail => {}:{} error: {}",name, value, e.toString());
        }
    }
}
